package cn.iune.erp.purchase;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;


@Repository
public class PurchaseOrderDetailDaoJPAImpl extends BaseJPAImpl<PurchaseOrderDetail> implements IPurchaseOrderDetailDao {

//	private final Logger log = LoggerFactory.getLogger(PurchaseOrderDetailDaoJPAImpl.class);

	private String kSql;
	
//	@PersistenceContext 
//	private EntityManager em ;


	@Override
	public void insert(PurchaseOrderDetail obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
		em.remove(em.getReference(PurchaseOrderDetail.class, fID));
	}

	@Override
	public PurchaseOrderDetail update(PurchaseOrderDetail obj) {
		PurchaseOrderDetail data = em.merge(obj);
		return data;
	}

	@Override
	public PurchaseOrderDetail getByID(String fID) {
		PurchaseOrderDetail singleResult = em.find(PurchaseOrderDetail.class, fID);
		return singleResult;
	}

	@Override
	public List<PurchaseOrderDetail> getAll() {
		Query query = em.createNamedQuery("PurchaseOrderDetail.findAll");
		@SuppressWarnings("unchecked")
		List<PurchaseOrderDetail> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public List<PurchaseOrderDetail> getByMasterID(String fMasterID) {
		// TODO Auto-generated method stub
		kSql="SELECT PurchaseOrderDetail FROM PurchaseOrderDetail PurchaseOrderDetail WHERE PurchaseOrderDetail.fMasterID=:fMasterID";
		Query query = em.createQuery(kSql);
		query.setParameter("fMasterID", fMasterID);
		@SuppressWarnings("unchecked")
		List<PurchaseOrderDetail> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public PurchaseOrderDetail getByNo(String stockNo, String serialNo, String enterpriseNo) {
		//1、定义sql语句
		kSql="SELECT PurchaseOrderDetail FROM PurchaseOrderDetail PurchaseOrderDetail "
				+ " WHERE ( PurchaseOrderDetail.stockNo = :stockNo ) "
				+ " AND ( PurchaseOrderDetail.serialNo = :serialNo ) "
				+ " AND ( PurchaseOrderDetail.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("stockNo", stockNo);
		query.setParameter("serialNo", serialNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		PurchaseOrderDetail singleResult = null;
		try{
			singleResult = (PurchaseOrderDetail) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}

	@Override
	public List<PurchaseOrderDetail> getByStorageNo(String storageNo, String factoryNo, String enterpriseNo) {
		// TODO Auto-generated method stub
		kSql="SELECT PurchaseOrderDetail "
				+ " FROM PurchaseOrderDetail PurchaseOrderDetail "
				+ " WHERE PurchaseOrderDetail.storageNo=:storageNo "
				+ " AND PurchaseOrderDetail.factoryNo=:factoryNo "
				+ " AND PurchaseOrderDetail.enterpriseNo=:enterpriseNo "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("storageNo", storageNo);
		query.setParameter("factoryNo", factoryNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<PurchaseOrderDetail> resultList = query.getResultList();
		return resultList;
	}

	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(PurchaseOrderDetail.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}

	@Override
	public JSONObject query(JSONObject data) throws SQLException{
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");
//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT PurchaseOrderDetail FROM PurchaseOrderDetail PurchaseOrderDetail %s %s ";
		String select = "PurchaseOrderDetail.*"
				+ ",if(PurchaseOrderDetail.itemProperty is null,PurchaseOrderDetail.itemName,CONCAT(PurchaseOrderDetail.itemName,'【',PurchaseOrderDetail.itemProperty,'】')) as itemDescribe"
				
				//待收货数量
				+ ",(PurchaseOrderDetail.itemAmount - PurchaseOrderDetail.storeItemIng - PurchaseOrderDetail.storeItemAmount) as pendingQuantity"
				+ ",(PurchaseOrderDetail.pieceQuantity - PurchaseOrderDetail.storePiece) as pendingPiece"

				+ ",FileItem.qualityType"
				+ ",FileItem.qualityTypeLabel"
				+ ",FileItem.batchNo"
				+ ",FileItem.qualityPeriod"
				+ ",FileItem.validDays"
				+ ",FileItem.checkoutAgainDays"
				+ ",FileItem.storeNo"
				+ ",FileItem.images"
				
//				+ ",FileItem.qualityStatus"
//				+ ",FileItem.qualityStatusLabel"
				;
		
//		String from = "PurchaseOrderDetail PurchaseOrderDetail";
		String from = "PurchaseOrderDetail PurchaseOrderDetail LEFT JOIN FileItem FileItem ON (FileItem.fID = PurchaseOrderDetail.itemID)";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("PurchaseOrderDetail.stockDetailNo LIKE ? OR PurchaseOrderDetail.itemName LIKE ? OR PurchaseOrderDetail.comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("PurchaseOrderDetail.fID='"+id+"'");
		}
		//处理fMasterID
//		System.out.println("fMasterID-->"+fMasterID);
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("PurchaseOrderDetail.fMasterID='"+fMasterID+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT PurchaseOrderDetail.fID FROM PurchaseOrderDetail PurchaseOrderDetail    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
		//////////////////////////////////自定义聚合数据/////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////
		String aggregateSelect = "";
		
		JSONObject aggregateColumns = data.getJSONObject("aggregateColumns"); // 聚合列定义
//		System.out.println("aggregateColumns-->"+aggregateColumns);
		if(aggregateColumns!=null){
			
			Set<String> keys = aggregateColumns.keySet();
			int index = 0;
			for(String key:keys){
				if(index==0){
					aggregateSelect = aggregateSelect + "SUM(" + key + ") as " + aggregateColumns.getJSONObject(key).getString("name");
				}else{
					aggregateSelect = aggregateSelect + ",SUM(" + key + ") as " + aggregateColumns.getJSONObject(key).getString("name");
				}
				
				index++;
			}
			
//			aggregateSelect = "SUM(StorageItem.quantityL) as sumQuantityL,SUM(CONVERT(FileItem.costingAmountPer*StorageItem.quantityL,decimal(38,2))) as sumCostingAmount,SUM(StorageItem.pieceQuantityL) as sumPieceQuantityL";
			
		}
		
//		String aggregate = data.getString("aggregate");
//		if(aggregate!=null){
//			if(aggregateSelect.equals("")){
//				aggregateSelect = aggregate;
//			}else{
//				aggregateSelect = aggregateSelect + "," + aggregate;
//			}
//		}
		
//		System.out.println("aggregateSelect-->"+aggregateSelect);
		
		if(!aggregateSelect.equals("")){
			//如果select不为空
			
			String aggregateSql = String.format(format, aggregateSelect, from, where, "");
//			System.out.println("aggregateSql-->"+aggregateSql);
			Table aggregateTable = DataUtils.queryData(conn, aggregateSql, sqlParams, aggregateColumns, 0, table.getTotal());
//			Row row = aggregateTable.getRows().get(0);
//			JSONObject aggregateValues = Transform.rowToJson(aggregateTable, row);
			JSONObject jo = Transform.tableToJson(aggregateTable);
			JSONArray jarray = jo.getJSONArray("rows");
			JSONObject aggregateValues = new JSONObject();
			if(jarray.size()>0){
				aggregateValues = jarray.getJSONObject(0);
			}
//			System.out.println("aggregateValues-->"+aggregateValues);
			//jb-->{"userdata":{"recordState":"none"},"costingAmount":{"value":"599517613.43"},"costingAmountPer":{"value":"59957.893727"}}
			json.put("aggregateValues", aggregateValues);
		}
		//////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////
		//关闭连接
		conn.close();
		return json;
	}


	
}
